package com.cqs.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Author:li
 * <p>
 * create date: 18-5-29 18:33
 */
public class MinimumDepthofBinaryTree111 {


    //DFS求解
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        //求左子树到叶子节点的最小深度
        int left = minDepth(root.left);
        //求左子树到叶子节点的最小深度
        int right = minDepth(root.right);

        //若出现有一边高度为０　说明有一方不存在叶子节点　
        //此时结果以另一边进行求解
        if (left == 0 || right == 0) {
            return Math.max(left, right) + 1;
        }
        //两边高度均不是０　最小的子树深度+1
        return Math.min(left, right) + 1;
    }

    //广度优先遍历
    public int minDepthWFS(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int high = 0;
        TreeNode node = null;
        while (!queue.isEmpty()) {
            int size = queue.size();
            //同一层
            for (int i = 0; i < size; i++) {
                node = queue.poll();
                //遍历结束条件
                if (node.left == null && node.right == null) {
                    return high + 1;
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            high += 1;
        }
        return high;
    }

}
